import java.net.*;
import java.io.*;
import java.util.*;


public class Tracker{
	
  private Vector<PrintWriter> _tabClients = new Vector<PrintWriter>();
  public Vector<String> _tabId = new Vector<String>();
  private int _nbClients=0;
  public Bdd _bdd = new Bdd();
  
  public static void main(String args[]){
    Tracker tracker = new Tracker(); 
    try{
      Integer port;
      if(args.length<=0) 
    	  port=new Integer("18000");
      else 
    	  port = new Integer(args[0]);
      new Commandes(tracker);
      ServerSocket ss = new ServerSocket(port.intValue()); 
      printWelcome(port);
      while (true){
        new TrackerThread(ss.accept(),tracker); 
      }
    }
    catch (Exception e) { }
  }

  static private void printWelcome(Integer port){
    System.out.println("Demarrage du Tracker sur le port : "+port.toString());
    System.out.println("--------");
    System.out.println("Quitter : tapez \"quit\"");
    System.out.println("Nombre de connectes : tapez \"total\"");
    System.out.println("--------");
  }



  synchronized public void sendAll(String message,String sLast){
    PrintWriter out; 
    for (int i = 0; i < _tabClients.size(); i++) {
      out = (PrintWriter) _tabClients.elementAt(i); 
      if (out != null) {

        out.print(message+sLast);
        out.flush();
     	System.out.println(message + "send\n");
      }
    }
  }


  synchronized public void delClient(int i){
    _nbClients--; 
    if (_tabClients.elementAt(i) != null){
      _tabClients.set(i,null); 
    }
    if(_tabId.elementAt(i)!=null){
    	_tabId.set(i,null);
    }
  }
 
  synchronized public void addId(int i,String ip,int port){
	    if (_tabClients.elementAt(i) != null){
	    	_tabId.set(i,ip+":"+String.valueOf(port));
	    }
	  }

  synchronized public boolean isClient(int i){
	  for (int j = 0; j < _tabClients.size(); j++){
		  if(_tabClients.elementAt(j)!=null){
			  if(_tabId.get(j).equals(_tabId.get(i)) && i!=j){
				  _tabId.set(i, String.valueOf(i));
				  return true;
			  }
		  }
	  }
	  return false;
  }
  
  synchronized public int addClient(PrintWriter out){
    _nbClients++;
    _tabClients.addElement(out);
    _tabId.addElement(String.valueOf(_nbClients));
    return _tabClients.size()-1;
  }

  synchronized public int getNbClients(){
    return _nbClients; 
  }

}

